package com.ly.web;

import com.ly.po.CoursesPO;
import com.ly.result.R;
import com.ly.service.CultivateService;
import com.ly.service.ExamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/cultivate")
public class CultivateController {

    @Autowired
    private CultivateService cultivateService;

    @Autowired
    private ExamService examService;

    /**
     * 根据当前班级的班级代码获得课程数据
     * @param classCode
     * @return
     */
    @GetMapping("/cultivate/class/{classCode}")
    public R getCourseListByClass(@PathVariable String classCode) {
        List<CoursesPO> coursesPOList = cultivateService.getCoursePOListByClassCode(classCode);
        return R.success(coursesPOList);
    }

    /**
     * 获取可添加的课程
     * @return
     */
    @PostMapping("/cultivate/available-courses")
    public R getAvailableCourseList(@RequestParam String classCode, @RequestParam String semester) {
        // 根据班级代码+学期获得所有可以添加的课程（在cultivate表中没有的）
        List<CoursesPO> coursesPOList = cultivateService.getAvailableCourse(classCode, semester);
        return R.success(coursesPOList);
    }

    /**
     * 将课程与班级绑定
     * @param classCode
     * @param semester
     * @param courseCodes
     * @return
     */
    @PostMapping("/cultivate/add-courses")
    public R addCourse(@RequestParam String classCode, @RequestParam String semester, @RequestParam String courseCodes) {
        List<String> courseCodeList = Arrays.asList(courseCodes.split(","));
        // 新增到cultivate表中
        cultivateService.saveCourseByClassCode(classCode, semester, courseCodeList);
        // 为班级相关的学生选课
        cultivateService.selectRequiredCourse(classCode, courseCodeList);

        return R.success(null, "添加成功");
    }

    /**
     * 将课程与班级解绑
     */
    @PostMapping("/cultivate/delete-courses")
    public R deleteCourse(@RequestParam String classCode, @RequestParam String semester, @RequestParam String courseCodes){
        List<String> courseCodeList = Arrays.asList(courseCodes.split(","));
        // 删除cultivate表中的记录
        cultivateService.deleteCourseByClassCode(classCode, semester, courseCodeList);
        // 删除班级内学生的相关课程
        cultivateService.deleteRequiredCourse(classCode, courseCodeList);
        // 删除课程相关的考试安排
        examService.deleteExamByCourseCodeList(courseCodeList);
        return R.success(null, "删除成功");
    }

}
